package org.imsetal.ilpointservice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.imsetal.ilpointservice.mapper.DailyCheckInMapper;
import org.imsetal.ilpointservice.mapper.UserpointMapper;
import org.imsetal.ilpointservice.pojo.DailyCheckIn;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class DailyCheckInService {
    @Resource
    DailyCheckInMapper daliyCheckInMapper;
    @Resource
    UserpointMapper userpointMapper;
    @Resource
    UserPointService userPointService;

    public String dailyCheckIn(Long userid) {
        if(!checkedToday(userid)){
            DailyCheckIn dailyCheckIn = new DailyCheckIn();
            dailyCheckIn.setUserid(userid);
            daliyCheckInMapper.insert(dailyCheckIn);
            userPointService.addUserPoint(userid,30);
            return "success";
        }else{
            return "今日已签到";
        }
    }

    public List<DailyCheckIn> getDailyCheckInListByUserId(Long userid) {
        List<DailyCheckIn> dailyCheckInList=daliyCheckInMapper.selectList(new QueryWrapper<DailyCheckIn>().eq("userid", userid));
        Collections.reverse(dailyCheckInList);
        return dailyCheckInList;
    }

    public boolean checkedToday(Long userid){
        QueryWrapper<DailyCheckIn> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("checkintime");
        queryWrapper.eq("userid", userid);
        List<DailyCheckIn> dailyCheckInList=daliyCheckInMapper.selectList(queryWrapper);
        if(dailyCheckInList.size()>0){
            System.out.println(dailyCheckInList.get(0).getCheckintime());
            return !isBefore(dailyCheckInList.get(0).getCheckintime());
        }else{
            return false;
        }
    }

    public boolean isBefore(String day){
        try {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String now = formatter.format(date);
            int nowYear = Integer.parseInt(now.substring(0, 4));
            int dayYear = Integer.parseInt(day.substring(0, 4));
            if(nowYear>dayYear)return true;
            else{
                int nowMonth = Integer.parseInt(now.substring(5,7));
                int dayMonth = Integer.parseInt(day.substring(5,7));
                if(nowMonth>dayMonth)return true;
                else{
                    int nowDay = Integer.parseInt(now.substring(8,10));
                    int dayDay = Integer.parseInt(day.substring(8,10));
                    if(nowDay>dayDay)return true;
                    else return false;
                }
            }
        }catch (NumberFormatException e){
            return true;
        }
    }
}
